<template>
    <div class="app-container">
      <!-- 搜索表单 -->
      <el-card shadow="never" class="search-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable />
          </el-form-item>
          <el-form-item label="性别">
                <el-select v-model="searchForm.sex" placeholder="请选择性别" style="width: 240px" clearable>
                    <el-option v-for="item in sexOptions" 
                    :key="item.value" 
                    :label="item.label" 
                    :value="item.value"/>
                </el-select>
            </el-form-item>
                <el-form-item label="等级">
                    <el-select v-model="searchForm.levelId" placeholder="请选择" style="width: 240px" clearable>
                        <el-option v-for="item in levelOptions" 
                        :key="item.id"
                        :label="item.name" 
                        :value="item.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="技能">
                    <el-select v-model="searchForm.specialtyId" placeholder="请选择" style="width: 240px" clearable>
                        <el-option v-for="item in specialtyOptions" 
                        :key="item.id"
                        :label="item.name" 
                        :value="item.id"/>
                    </el-select>
                </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="searchForm.address" placeholder="请输入地址" clearable />
          </el-form-item>
  
          <el-form-item label="认证状态">
            <el-select v-model="searchForm.authentication" placeholder="请选择" style="width: 240px" clearable>
                 <el-option v-for="item in authOptions" :key="item.value"
                    :label="item.label" :value="item.value"/>
                    </el-select>
                </el-form-item>
  
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
  
      <!-- 操作按钮 -->
      <div class="mb-4">
        <el-button type="primary" @click="openDialog()">添加咨询师</el-button>
        <el-button type="danger" :disabled="!selectedIds.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table :data="tableData"  @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="70" align="center"  />
        <el-table-column prop="id" label="ID" width="100" align="center" />
        <el-table-column prop="name" label="姓名" width="100" align="center" />
        <el-table-column label="性别" width="0" align="center">
          <template #default="prop">
            {{ prop.row.sex === 'M' ? '男' : '女' }}
            <!-- {{ row }} -->
          </template>
        </el-table-column>
        <el-table-column label="等级" align="center" width="150">
          <template #default="prop">
            {{ prop.row.consultLevel?.name || '未设置' }}
          </template>
        </el-table-column>
        <el-table-column label="技能" align="center" width="100">
          <template #default="">
    <el-tag   v-for="spec in specialtyOptions" :key="spec"
                 style="margin-right:5px">
      {{ spec.name }}
      <!-- <el-tag   v-for="spec in prop.row.specialties" :key="spec.id"
                 style="margin-right:5px">
      {{ spec.name }}
    </el-tag> -->
    </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center" width="100">
            <template #default="prop" >
              <img style="width: 50px;height: 50px;" v-if="prop.row.img" :src="url +prop.row.img" class="avatar" />
            </template>
          </el-table-column>
        <el-table-column prop="address" label="地址" align="center" width="260"  />
        <el-table-column prop="intro" label="简介" align="center" width="260">
          <template #default="scope">
            <el-text class="w-150px mb-2" truncated>
              {{ scope.row.intro }}
            </el-text>
            </template>
          </el-table-column>
        <el-table-column label="认证状态" width="170" align="center">
          <template #default="prop">
            <el-tag :type="prop.row.authentication ? 'success' : 'danger'">
              {{prop.row.authentication ? '已认证' : '未认证' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center" >
          <template #default="prop">
            <el-button link  @click="openDialog(prop.row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(prop.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页 -->
      <div class="mt-4">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchData"
          @current-change="fetchData"
        />
      </div>
  
      <!-- 添加/编辑对话框 -->
      <el-dialog 
        v-model="dialogVisible" 
        :title="isEdit ? '编辑咨询师' : '添加咨询师'" 
        width="600px"
      >
        <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名" />
          </el-form-item>
  
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="formData.sex">
              <el-radio label="M">男</el-radio>
              <el-radio label="F">女</el-radio>
            </el-radio-group>
          </el-form-item>
  
          <el-form-item label="等级" prop="levelId">
            <el-select v-model="formData.levelId" placeholder="请选择等级">
              <el-option
                v-for="level in levelOptions"
                :key="level.id"
                :label="level.name"
                :value="level.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="擅长技能" prop="specialtyId">
              <el-select
                v-model="formData.specialtyId"
                multiple
                placeholder="请选择技能"
                style="width: 100%"
              >
                <el-option
                  v-for="item in specialtyOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
            </el-select>
</el-form-item>
          
          <el-form-item label="图片" label-width="formLabelWidth" prop="img">
            <el-upload
  class="avatar-uploader"
  :action="uploadUrl"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
  :show-file-list="false"
>
  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
      </el-form-item>
  
          <el-form-item label="地址" prop="address">
            <el-input v-model="formData.address" placeholder="请输入地址" />
          </el-form-item>
  
          <el-form-item label="简介" prop="intro">
            <el-input v-model="formData.intro" type="textarea" :rows="3" />
          </el-form-item>
  
          <el-form-item label="认证状态">
            <el-switch
              v-model="formData.authentication"
              :active-value="1"
              :inactive-value="0"
            />
          </el-form-item>
        </el-form>
  
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
 import { ref, reactive, onMounted } from 'vue'
import axios from 'axios' // 引入 axios
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([])
const selectedIds = ref([])
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
// 常量定义
const uploadUrl = 'http://localhost:8080/file/upload'; // 图片上传地址
const url = ref('http://localhost:8080/file/downLoad?fileName=');  // 图片下载地址
// 搜索表单
const searchForm = reactive({
  name: '',
  sex: '',
  levelId: null,
  address: '',
  authentication: null,
  specialtyId:{}
})
//性别选项
const sexOptions=[
    {label:'男',value:'M'},
    {label:'女',value:'F'}
]
// 等级选项
const levelOptions = ref([])
//认证状态选项
const authOptions=[
    {label:'已认证',value:1},
    {label:'未认证',value:0}
]
// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()
const formData = reactive({
  id: null,
  name: '',
  sex: 'M',
  levelId: null,
  specialtyId:[],
  img: '',
  address: '',
  intro: '',
  authentication: 0
})
const fileList=ref([])
const imageUrl=ref('');
// 图片上传成功回调
const handleAvatarSuccess = (response) => {
  if (response && response.code === 1) {
    formData.img = response.data; // 存储文件名到表单数据
    imageUrl.value = url.value + response.data; // 预览完整路径
    
  } else {
    ElMessage.error('图片上传失败');
  }
};

// 图片上传前的校验
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
  }
  return isImage;
};
// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  levelId: [{ required: true, message: '请选择等级', trigger: 'change' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
}

// 初始化数据
onMounted(() => {
  fetchData();
  fetchLevelOptions();
  fetchSpecialtyOptions();
})
const specialtyOptions = ref([]); // 新增技能选项变量

function fetchSpecialtyOptions() {
  const params = {
    name: '', // 根据需求设置合适的值 
  }
  axios.get('/specialty/list',params)
    .then((res) => {
      if (res.data.code === 1) {
        specialtyOptions.value = res.data.data.list;
        console.log('获取技能选项成功:', specialtyOptions.value);
      }
    })
    .catch(error => {
      ElMessage.error('获取技能选项失败');
    });
}
// 获取等级选项
function fetchLevelOptions() {
    const params = {
    name: '', // 根据需求设置合适的值
  };
  axios
   .get('/consult-level/selectAll', { params })
   .then((res) => {
      console.log('获取等级选项响应:', res.data); // 打印响应数据用于调试
      if (res.status === 200 && res.data && res.data.data && Array.isArray(res.data.data.list)) {
        levelOptions.value = res.data.data.list;
      } else {
        console.error('接口返回数据格式不正确:', res.data);
        ElMessage.error('获取等级选项失败，接口返回数据格式不正确');
      }
    })
   .catch((error) => {
      console.error('获取等级选项失败:', error);
      if (error.response) {
        ElMessage.error(`获取等级选项失败，状态码: ${error.response.status}`);
      } else {
        ElMessage.error('获取等级选项失败，网络错误');
      }
    });
}

// 获取表格数据
function fetchData() {
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchForm
  }
  console.log('请求表格数据参数:', params); // 打印请求参数用于调试
  axios.get('/consult/selectAll', { params }) // 修改接口地址
    .then(res => {
      tableData.value = res.data.data.list.map(item => ({
       ...item,specialties:item.specialtyList || []
      }))
      total.value = res.data.data.total
    })
    .catch(error => {
      console.error('获取数据失败:', error)
      ElMessage.error('获取数据失败')
    })
    .finally(() => {
    })
}

// 搜索
const handleSearch = async () => {
  let consultIds = [];
  
  // 如果选择了技能，先获取关联的咨询师ID
  if (searchForm.specialtyId.length>0) {
    const { data } = await axios.post('/consultSpecialty/selectAll', { 
      specialtyIds: searchForm.specialtyId 
    });
    consultIds = data.data.map(item => item.consultId);
  }

  // 获取咨询师列表（需分页）
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    ...searchForm,
    // 传递consultIds给后端（需确保后端接口支持）
      // name: searchForm.name ? `%${searchForm.name}%` : undefined, // 添加模糊查询通配符
    consultIds:consultIds.length>0?consultIds:null
  };
  
  const res = await axios.get('/consult/selectAll', { params });
  tableData.value = res.data.data.list;
  total.value = res.data.data.total;
};

// 重置搜索
function resetSearch() {
  Object.assign(searchForm, {
    name: '',
    sex: '',
    levelId: null,
    address: '',
    authentication: null
  })
  fetchData()
}

// 表格多选
function handleSelectionChange(selection) {
  selectedIds.value = selection.map(item => item.id)
}

// 打开对话框
function openDialog(row) {
  if (row) {
    isEdit.value = true
    Object.assign(formData,{...row,specialtyId:row.specialties.map(item=>item.id) || []})
    // formData.img = row.img; // 确保img字段被赋值
    imageUrl.value = row.img ? url.value + row.img : '';
    // fileList.value = row.img ? [{ name: '图片', url: url.value + row.img }] : [];
  } else {
    // isEdit.value = false
    // imageUrl.value = '';
    // fileList.value = [];
    resetForm()
  }
  dialogVisible.value = true
}

// 重置表单
function resetForm() {
  formRef.value?.resetFields()
  Object.assign(formData, {
    id: null,
    name: '',
    sex: 'M',
    levelId: null,
    img: '',
    address: '',
    intro: '',
    authentication: 0
  })
  imageUrl.value = '';
  fileList.value = [];
}

// 提交表单
function submitForm() {
  formRef.value.validate(valid => {
    if (!valid) return
    const requestData={
      ...formData,
      specialtyIds:formData.specialtyId
    };
    const request = isEdit.value
      ? axios.put('/consult', requestData) // 修改接口地址
      : axios.post('/consult', requestData) // 修改接口地址
    request
      .then(() => {
        ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
        dialogVisible.value = false
        fetchData()
      })
      .catch(error => {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      })
  })
}
// 单个删除
function handleDelete(id) {
  ElMessageBox.confirm('确定删除该咨询师吗？', '提示', { type: 'warning' })
    .then(() => {
      axios.delete(`/consult/${id}`) // 修改接口地址
        .then(() => {
          ElMessage.success('删除成功')
          fetchData()
        })
        .catch(error => {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        })
    })
    .catch(() => {})
}

// 批量删除
function handleBatchDelete() {
  ElMessageBox.confirm('确定删除选中的咨询师吗？', '提示', { type: 'warning' })
    .then(() => {
      axios.delete('/consult/deleteBatch', { data: selectedIds.value }) // 修改接口地址
        .then(() => {
          ElMessage.success('批量删除成功')
          selectedIds.value = []
          fetchData()
        })
        .catch(error => {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        })
    })
    .catch(() => {})
}

  </script>
  
  <style scoped>
  .search-card {
    margin-bottom: 20px;
  }
  .avatar-uploader :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  .avatar-uploader :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    text-align: center;
  }
  .avatar {
    width: 120px;
    height: 120px;
    display: block;
  }
  </style>